#encoding: utf-8

=begin

代销结算记账程序，在update-tags.rb中周期调用

所有未结算的代销订单（paid==1&&source_mid>0&&settle==0)，如果consign_due==0 ，则计算该订单应分给代销商的分成，记录入consign_due
代销订单不处理涉及到退货的状态，如果有发生退款，代销双方应自行线下核对后离线处理

=end

load 'rds_api.rb'

def get_uncleared_consign_orders
  consigns = []
  #sql = "select * from crmeb.eb_store_order where paid = 1 and source_mid > 0 and settle = 0 and (consign_due < 0.01 and consign_left < 0.01);" #测试时用的每次重置模式
  sql = "select * from crmeb.eb_store_order where paid = 1 and source_mid > 0 and settle = 0;" #测试时用的每次重置模式
  queryRds(sql).each { |q| consigns += [q] }
  return consigns
end

=begin 
  订单所有商品都是代销,获得应计提成额的方法是
  1)先获得该订单的计价总额（支付+积分+用券）M
  2)按代销商品分别计算计价金额t后汇总T
  3)按代销商品分别计算分成金额c后汇总C
  4)用C/T获得分成比例，最后乘以订单计价总额A
  不能用用户折扣直接计算，因为用户折扣率可能在订单完成后有变化
=end
def calc_consign_due consign

  consign_due = 0.0

  cart_ids = JSON.parse consign['cart_id']
  return 0.0 if cart_ids.size < 1 #小心使得万年船，这只是直觉

  priceM = consign['total_price']+consign['deduction_price']+consign['coupon_price']

  priceT = 0.0
  priceC = 0.0
  sql = "select id, product_id, product_attr_unique, cart_num from crmeb.eb_store_cart where id in (#{cart_ids.join(',')}) and is_pay = 1;"

  queryRds(sql).each do |q|

    pid = q['product_id']
    consign_ratio = 0
    inq = "select consign_ratio from crmeb.eb_store_product where id = #{pid};"
    queryRds(inq).each { |r| consign_ratio = r['consign_ratio'] }

    puniq = q['product_attr_unique']
    num = q['cart_num']
    price = 0.0
    inq = "select price from crmeb.eb_store_product_attr_value where `unique`='#{puniq}' and type = 0 and product_id = #{pid};"
    queryRds(inq).each do |r|
      price = r['price']
      break
    end
    priceT += price*num
    priceC += price*num*consign_ratio
  end

  consign_due = priceM * priceC/priceT if priceT>0
  return consign_due

end

def register_consign_info consign
  consign_due_comment = "M#{consign['mer_id']}代M#{consign['source_mid']}销" 
  if consign['refund_price'] > 0
    consign_due_comment += " | 有退款需二清" 
    consign_due = 0.0
  else
    consign_due = calc_consign_due consign
  end
  consign_left = consign['total_price'] + consign['deduction_price'] + consign['coupon_price'] - consign['refund_price'] - consign_due
  sql = "update crmeb.eb_store_order set consign_due = #{consign_due.to_f.round 2}, consign_left = #{consign_left.to_f.round 2}, consign_due_comment = '#{consign_due_comment}' where id = #{consign['id']};"
  queryRds sql
end

consigns = get_uncleared_consign_orders
consigns.each do |consign|
  register_consign_info consign
end

puts "done. #{consigns.size}"
